{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# MULTI-LAYER PERCEPTRON WITH CUSTOM DATA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Packages loaded\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline  \n",
    "print (\"Packages loaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# LOAD DATA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['trainlabel', 'imgsize', 'trainimg', 'testimg', 'testlabel', 'use_gray']\n",
      "408 train images loaded\n",
      "273 test images loaded\n",
      "4096 dimensional input\n",
      "Image size is [64 64]\n",
      "4 classes\n"
     ]
    }
   ],
   "source": [
    "# Load them!\n",
    "cwd = os.getcwd()\n",
    "loadpath = cwd + \"/data/custom_data.npz\"\n",
    "l = np.load(loadpath)\n",
    "\n",
    "# See what's in here\n",
    "print (l.files)\n",
    "\n",
    "# Parse data\n",
    "trainimg = l['trainimg']\n",
    "trainlabel = l['trainlabel']\n",
    "testimg = l['testimg']\n",
    "testlabel = l['testlabel']\n",
    "imgsize = l['imgsize']\n",
    "ntrain = trainimg.shape[0]\n",
    "nclass = trainlabel.shape[1]\n",
    "dim    = trainimg.shape[1]\n",
    "ntest  = testimg.shape[0]\n",
    "print (\"%d train images loaded\" % (ntrain))\n",
    "print (\"%d test images loaded\" % (ntest))\n",
    "print (\"%d dimensional input\" % (dim))\n",
    "print (\"Image size is %s\" % (imgsize))\n",
    "print (\"%d classes\" % (nclass))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DEFINE NETWORK"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Network Ready to Go!\n"
     ]
    }
   ],
   "source": [
    "tf.set_random_seed(0)\n",
    "# Parameters\n",
    "learning_rate   = 0.001\n",
    "training_epochs = 200\n",
    "batch_size      = ntrain\n",
    "display_step    = 20\n",
    "\n",
    "# Network Parameters\n",
    "n_hidden_1 = 128 # 1st layer num features\n",
    "n_hidden_2 = 128 # 2nd layer num features\n",
    "n_input    = dim # data input \n",
    "n_classes  = nclass # total classes (0-9 digits)\n",
    "\n",
    "# tf Graph input\n",
    "x = tf.placeholder(\"float\", [None, n_input])\n",
    "y = tf.placeholder(\"float\", [None, n_classes])\n",
    "\n",
    "# Create model\n",
    "def multilayer_perceptron(_X, _weights, _biases):\n",
    "    layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1'])) \n",
    "    layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2']))\n",
    "    return tf.matmul(layer_2, _weights['out']) + _biases['out']\n",
    "    \n",
    "# Store layers weight & bias\n",
    "stddev = 0.1 # <== This greatly affects accuracy!! \n",
    "weights = {\n",
    "    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=stddev)),\n",
    "    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),\n",
    "    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev=stddev))\n",
    "}\n",
    "biases = {\n",
    "    'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n",
    "    'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n",
    "    'out': tf.Variable(tf.random_normal([n_classes]))\n",
    "}\n",
    "print (\"Network Ready to Go!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DEFINE FUNCTIONS"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Functions ready\n"
     ]
    }
   ],
   "source": [
    "# Construct model\n",
    "pred = multilayer_perceptron(x, weights, biases)\n",
    "\n",
    "# Define loss and optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) \n",
    "optm = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n",
    "corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))    \n",
    "accr = tf.reduce_mean(tf.cast(corr, \"float\"))\n",
    "\n",
    "# Initializing the variables\n",
    "init = tf.initialize_all_variables()\n",
    "print (\"Functions ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# OPTIMIZE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 000/200 cost: 1.271932960\n",
      " Training accuracy: 0.723\n",
      " Test accuracy: 0.707\n",
      "Epoch: 020/200 cost: 0.485024929\n",
      " Training accuracy: 0.831\n",
      " Test accuracy: 0.817\n",
      "Epoch: 040/200 cost: 0.269245446\n",
      " Training accuracy: 0.926\n",
      " Test accuracy: 0.857\n",
      "Epoch: 060/200 cost: 0.158787951\n",
      " Training accuracy: 0.973\n",
      " Test accuracy: 0.883\n",
      "Epoch: 080/200 cost: 0.054250188\n",
      " Training accuracy: 0.993\n",
      " Test accuracy: 0.905\n",
      "Epoch: 100/200 cost: 0.034250565\n",
      " Training accuracy: 0.998\n",
      " Test accuracy: 0.908\n",
      "Epoch: 120/200 cost: 0.016527731\n",
      " Training accuracy: 1.000\n",
      " Test accuracy: 0.905\n",
      "Epoch: 140/200 cost: 0.013574737\n",
      " Training accuracy: 1.000\n",
      " Test accuracy: 0.894\n",
      "Epoch: 160/200 cost: 0.006475344\n",
      " Training accuracy: 1.000\n",
      " Test accuracy: 0.894\n",
      "Epoch: 180/200 cost: 0.004590446\n",
      " Training accuracy: 1.000\n",
      " Test accuracy: 0.894\n",
      "Optimization Finished!\n"
     ]
    }
   ],
   "source": [
    "# Launch the graph\n",
    "sess = tf.Session()\n",
    "sess.run(init)\n",
    "\n",
    "# Training cycle\n",
    "for epoch in range(training_epochs):\n",
    "    avg_cost = 0.\n",
    "    total_batch = int(ntrain/batch_size)\n",
    "    # Loop over all batches\n",
    "    for i in range(total_batch):\n",
    "        randidx = np.random.randint(ntrain, size=batch_size)\n",
    "        batch_xs = trainimg[randidx, :]\n",
    "        batch_ys = trainlabel[randidx, :]   \n",
    "        # Fit training using batch data\n",
    "        sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        # Compute average loss\n",
    "        avg_cost += sess.run(cost, \n",
    "                feed_dict={x: batch_xs, y: batch_ys})/total_batch\n",
    "        # Display logs per epoch step\n",
    "    if epoch % display_step == 0:\n",
    "        print (\"Epoch: %03d/%03d cost: %.9f\" % \n",
    "               (epoch, training_epochs, avg_cost))\n",
    "        train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        print (\" Training accuracy: %.3f\" % (train_acc))\n",
    "        test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel})\n",
    "        print (\" Test accuracy: %.3f\" % (test_acc))\n",
    "\n",
    "print (\"Optimization Finished!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# CLOSE SESSION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Session closed.\n"
     ]
    }
   ],
   "source": [
    "sess.close()\n",
    "print (\"Session closed.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
